package handler

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"zg5/zk1/goods-management/common/global"
	"zg5/zk1/goods-management/common/proto/goods"
	"zg5/zk1/goods-management/goods_server/internal/model"
	"zg5/zk1/goods-management/pkg"
)

type Server struct {
	goods.UnimplementedGoodsSrvServer
}

// AddGoods 商品发布
func (s *Server) AddGoods(_ context.Context, req *goods.AddGoodsRequest) (*goods.AddGoodsResponse, error) {
	//开启事务
	tx := global.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	number := uuid.NewString()
	//创建商品信息
	newGoods := model.Goods{
		Images:      req.Images,
		Name:        req.Name,
		Number:      number,
		TypesId:     req.TypesId,
		StockpileId: req.StockpileId,
		Price:       req.Price,
	}
	if err := tx.Debug().Create(&newGoods).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("商品信息创建失败")
	}
	//创建商品规格表
	goodsDetails := model.GoodsDetails{
		GoodsId: newGoods.Id,
	}
	if err := tx.Debug().Create(&goodsDetails).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("商品规格创建失败")
	}
	//创建商品规格属性
	goodsDetailsAttribute := model.GoodsDetailsAttribute{
		GoodsDetailsId: goodsDetails.Id,
		K:              req.K,
		V:              req.V,
		Price:          req.Price,
		Stockpile:      req.Stockpile,
	}
	if err := tx.Debug().Create(&goodsDetailsAttribute).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("商品规格属性创建失败")
	}
	tx.Commit()
	return &goods.AddGoodsResponse{}, nil
}

// GoodsList 商品列表
func (s *Server) GoodsList(_ context.Context, req *goods.GoodsListRequest) (*goods.GoodsListResponse, error) {
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.Page
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var count int64
	global.DB.Debug().Model(&model.Goods{}).Count(&count)
	//根据状态进行筛选
	var goodsList []model.Goods
	global.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Where("status = ?", req.Status).Find(&goodsList)
	var lists []*goods.GoodsList
	for _, m := range goodsList {
		var types model.Types
		global.DB.Debug().Where("id = ?", m.TypesId).Find(&types)
		lists = append(lists, &goods.GoodsList{
			GoodsId:   m.Id,
			Images:    m.Images,
			Name:      m.Name,
			Number:    m.Number,
			Price:     m.Price,
			Sales:     m.Sales,
			TypesName: types.TypesName,
			Status:    uint64(m.Status),
			CreatedAt: m.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	pkg.SyncToEs()
	return &goods.GoodsListResponse{
		List:  lists,
		Count: uint64(count),
	}, nil
}
